package com.xu.sys.servlet;

import com.xu.sys.bean.SysMenu;
import com.xu.sys.bean.SysUser;
import com.xu.sys.service.IMenuService;
import com.xu.sys.service.IUserService;
import com.xu.sys.service.impl.IUserServiceimpl;
import com.xu.sys.service.impl.MenuServiceimpl;
import com.xu.sys.utils.Constant;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "loginServlet",urlPatterns = {"/sys/loginServlet"})
public class loginServlet extends HttpServlet {
    private IUserService  service = new IUserServiceimpl();

    private IMenuService  menuService = new MenuServiceimpl();


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 做登录认证的操作
        String userName = req.getParameter("userName");
        String password = req.getParameter("password");
        // 根据账号去数据库查询记录
        SysUser user = service.findByName(userName);
        if(user == null ){
            // 账号不存在
            req.setAttribute("msg","登录失败!账号不存在");
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }else if(!password.equals(user.getPassword())){
            // 密码不正确
            req.setAttribute("msg","登录失败!密码错误...");
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }else{
            // 说明登录成功
            // 那么我们需要记录当前登录的用户
            HttpSession session = req.getSession();
            user.setPassword(null); // 记录的账号把密码置空。安全考虑
            session.setAttribute(Constant.LOGIN_USER,user);
            //登录成功后获取当前用户的菜单信息
            Integer roleId = user.getRoleId();
            if (roleId != null){
                //查询对应的菜单信息
                List<SysMenu> menus = menuService.findByRoleId(roleId);
                session.setAttribute(Constant.LOGIN_MENUS,menus);
            }
            resp.sendRedirect("/main.jsp");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
